<?php

function login(){
	if(isset($_SESSION['edoc_user'])){
		$user = $_SESSION['edoc_user'];
		$pass = $_SESSION['edoc_pass'];
	}else{
		$user = $_POST['uname'];
		$pass = moo_crypt($_POST['pword']);
	}
	$q = "SELECT * FROM view_user where user_name='$user' and user_passwd='$pass';";
	$r = getPG($q);
	if(!$r[0]) return false;
	else{
		$_SESSION['edoc_user'] = $user;
		$_SESSION['edoc_pass'] = $pass;
		$_SESSION['edoc_user_id'] = $r[0]['user_id'];
		$_SESSION['edoc_read'] = $r[0]['read']; //0=none 1=only own 2=all
		$_SESSION['edoc_write'] = $r[0]['write']; //0=none 1=only own 2=all
		$_SESSION['edoc_type'] = $r[0]['user_type']; //0=admin 1=normal
		$_SESSION['edoc_depart_id'] = $r[0]['depart_id'];
		$_SESSION['edoc_depart'] = $r[0]['depart_name'];
		$_SESSION['edoc_secret'] = $r[0]['secret'];
	}
	return true;
}

function moo_crypt($input){
	$key1 = '$1$edocdead$';
	$key2 = '$1$sesesese$';
	$key3 = '$1$xoneedoc$';

	$encrypted_data = crypt($input, $key1);
	$encrypted_data = explode($key1,$encrypted_data);

	$encrypted_data = crypt($encrypted_data[1], $key2);
	$encrypted_data = explode($key2,$encrypted_data);

	$encrypted_data = crypt($encrypted_data[1], $key3);
	$encrypted_data = explode($key3,$encrypted_data);

	return $encrypted_data[1];
}

function addlog($oper,$detail){
	$id = getPG("select nextval('log_log_id_seq');");
	$id = $id[0]['nextval'];

	$q = "insert into log (log_id,user_id,user_name,depart_id,depart_name,operation,detail) values ($id,".$_SESSION['edoc_user_id'].",'".$_SESSION['edoc_user']."',".$_SESSION['edoc_depart_id'].",'".$_SESSION['edoc_depart']."','$oper','$detail');";
	updatePG($q);
}

?>
